package com.common.util.validators;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

import com.facade.MemberFacade;
import com.model.Member;


@FacesValidator("memberNRICValidator")
public class MemberNRICValidator implements Validator{
	
	@Override
	public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
		
		Member preloadMember = (Member)FacesContext.getCurrentInstance().getExternalContext().getApplicationMap().get("validatorMemberUpdate");
		
		MemberFacade memberFacade = new MemberFacade();
		Member member = memberFacade.findMemberWithNRIC(value.toString());
		
		if(preloadMember != null && member != null && preloadMember.getNric().equals(value)){
			member = null;
		}
		
		if(member != null){
			FacesMessage msg = new FacesMessage("NRIC/Passport No. Validation Failed.", "NRIC/Passport No. already exist");
			msg.setSeverity(FacesMessage.SEVERITY_ERROR);
			throw new ValidatorException(msg);
		}
	}
	
	
}
